package com.test.videoplayer.activity.rabbit;

import android.os.SystemClock;
import android.util.Log;

import com.rabbitmq.client.AlreadyClosedException;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;

/**
 * Created by zdk on 2019/11/28
 */
public class RabbitMQUtil {
    private final String TAG = "RabbitMQ";
    private static RabbitMQUtil singleton;
    private RabbitMQClient rabbitMQ;
    private ExecutorService executor;

    /**
     * 建议：
     * 在application中关闭或者在结束工作时关闭
     */
    public static void initService(String hostIp, int port, String username, String password) {
        RabbitMQClient.SERVICE_HOST_IP = hostIp;
        RabbitMQClient.SERVICE_PORT = port;
        RabbitMQClient.SERVICE_USERNAME = username;
        RabbitMQClient.SERVICE_PASSWORD = password;
    }


    private RabbitMQUtil() {
        rabbitMQ = RabbitMQClient.getInstance();
        executor = Executors.newSingleThreadExecutor();  //根据项目需要设置常用线程个数
    }

    public static RabbitMQUtil getInstance() {
        if (singleton == null) {
            synchronized (RabbitMQClient.class) {
                if (singleton == null) {
                    singleton = new RabbitMQUtil();
                }
            }
        }
        return singleton;
    }

    public void receiveQueueMessage(final String queueName, final ReceiveMessageListener listener) {
        executor.execute(() -> {
            while (singleton != null) {
                try {
                    rabbitMQ.receiveQueueMessageTest(queueName, message -> {
                        if (listener != null) listener.receiveMessage(message);
                        //Log.d(TAG, "message-" + message);
                    });
                    break;
                } catch (IOException | TimeoutException | AlreadyClosedException e) {
                    e.printStackTrace();
                    Log.d(TAG, "未连接到-" + queueName + "-----5秒后自动重连");
                    SystemClock.sleep(5000);
                }
            }
        });
    }

    /**
     * 建议：
     * 在application中关闭或者在结束工作时关闭
     */
    public void close() {
        rabbitMQ.close();
        executor.shutdownNow();
        singleton = null;
        Log.d(TAG, "关闭RabbitMQ");
    }

    public interface ReceiveMessageListener {
        void receiveMessage(String message);
    }

}
